package com.epro.dx.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.adapter.CountryListSearchAdapter;
import com.epro.dx.adapter.PinnedHeaderAdapter;
import com.epro.dx.pullview.IndexBarView;
import com.epro.dx.pullview.PinnedHeaderListView;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.MapUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CountryModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;

/**
 * 加载国家列表
 * @author  qsc
 * @version  [版本号, 2015-3-16]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class ChangeCountryActivity extends BaseFragmentActivity
{
    /**
     * 从前一个页面传过来的国家列表
     */
    private ArrayList<String> listCountry;
    
    /**
     * 从前一个页面传递过来的国家信息
     */
    private String countryName;
    
    ArrayList<Integer> mListSectionPos;
    
    ArrayList<String> mListItems;
    
    PinnedHeaderListView mListView;
    ListView mListViewSearch;
    
    PinnedHeaderAdapter mAdaptor;
    
    //搜索框
    TextView tv_serch;
    ArrayList<String> searchList;
    
    /**
     * 获取国家吗
     */
    private CountryModel countryModel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Tracker tracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
        tracker.setScreenName(ChangeCountryActivity.class.getSimpleName());
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_country_list);
        setTitleContent(getString(R.string.title_country));
        setLeftBtnContent(true, -1);
        Bundle bundle = getIntent().getExtras();
        if(null==bundle){
        	finish();
        }
        countryName = bundle.getString("countryName");
        listCountry = bundle.getStringArrayList("listCountry");
        initView();
        
        mListSectionPos = new ArrayList<Integer>();
        mListItems = new ArrayList<String>();
        searchList = new ArrayList<String>();
        
        if (savedInstanceState != null)
        {
            mListItems = savedInstanceState.getStringArrayList("mListItems");
            mListSectionPos = savedInstanceState.getIntegerArrayList("mListSectionPos");
            
            if (mListItems != null && mListItems.size() > 0 && mListSectionPos != null && mListSectionPos.size() > 0)
            {
                setListAdaptor();
            }
            
        }
        else
        {
        	if(null==listCountry){
        		AsyncTaskUtil.executeTask(new CountryInfoAsyncTask());
        	}else{
        		new Poplulate().execute(listCountry);
        	}
            
        }
    }
    
    @Override
    protected void onStart() {
    	super.onStart();
    	initEvent();//加载事件
    }
    
    /**
     * 加载事件
     */
    private void initEvent() {
    	
		// 文本框内容变化监听
    	tv_serch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				//当文本内容变化之后调用判断
				String text = s.toString();
				//将之前的数据清空
				searchList.clear();
				//System.out.println("mlistView======================="+text);
				if(TextUtils.isEmpty(text)){
					//为空显示全部国家列表
					mListView.setVisibility(View.VISIBLE);
					mListViewSearch.setVisibility(View.GONE);
				}else{
					//搜索过滤不为空，对输入文本进行匹配
					if(listCountry!=null){
						for(String countryName : listCountry){
							if(countryName.startsWith(text.toUpperCase())){
								searchList.add(countryName);
								System.out.println("countryList>>>>>>>>>>>>>>"+countryName);
							}
						}
					}
					mListView.setVisibility(View.GONE);
					mListViewSearch.setVisibility(View.VISIBLE);
					mListViewSearch.setAdapter(new CountryListSearchAdapter(getApplicationContext(), searchList));
				}
				
			}
		});
		
    	//mListViewSearch的条目点击事件
    	mListViewSearch.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 被点击，将相应的数据回传到原界面
				Intent intent = new Intent();
				intent.putExtra("countryName", searchList.get(position));
                intent.putExtra("countryModel", countryModel);
                ChangeCountryActivity.this.setResult(ServerConstant.Parameter.CHANGE_COUNTRY_RESULTCODE, intent);
                //mAdaptor.notifyDataSetInvalidated();
                ChangeCountryActivity.this.finish();
			}
		});
	}

	/**
     * 加载国家列表
     * @author  qsc255
     * @version  [版本号, 2015-2-3]
     * @see  [相关类/方法]
     * @since  [产品/模块版本]
     */
    protected class CountryInfoAsyncTask extends AsyncTask<Void, Void, String>
    {
        
        @Override
        protected void onPreExecute()
        {
            showWaitingDialog();
        }
        
        @Override
        protected String doInBackground(Void... params)
        {
            try
            {
                if (null != BaseFragmentActivity.countryPreferences
                    && !BaseFragmentActivity.countryPreferences.getAll().isEmpty())
                {
                    countryModel = new CountryModel();
                    countryModel.setAllCountry(BaseFragmentActivity.countryPreferences.getAll());
                }
                else
                {
                    //FIXME 该部分代码需要优化
                    if (null == countryPreferences)
                    {
                        countryPreferences = getSharedPreferences("countryData", MODE_PRIVATE);
                    }
                    countryModel = ProviderFactory.createUserServiceProvider().allCountry();
                    BaseFragmentActivity.persistenceCountry(countryModel.getAllCountry());
                }
            }
            catch (DxException e)
            {
                
                return e.getErrCode();
            }
            catch (Exception e)
            {
                Logger.e("ChangeCountryActivity", "OrderInfoAsyncTask", e);
            }
            return "0";
        }
        
        @Override
        protected void onPostExecute(String result)
        {
        	if(!isFinishing()){
        		hideWaitingDialog();
                if ("0".equals(result))
                {
                	listCountry = (ArrayList<String>)MapUtil.getValues(countryModel.getAllCountry());
                	new Poplulate().execute(listCountry);
                }
                else
                {
                    
                    AlertToast.alert(ChangeCountryActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
        	}
            
        }
    }
    
    /** 初始化控件
     * @see [类、类#方法、类#成员]
     */
    @SuppressLint("NewApi") private void initView()
    {
        mListView = (PinnedHeaderListView)findViewById(R.id.list_view);
        mListViewSearch = (ListView) findViewById(R.id.list_view_search);
        tv_serch = (TextView) findViewById(R.id.edtxt_search);
        
        //设置lv可过滤
        //mListView.setTextFilterEnabled(true);
        tv_serch.setImeOptions(EditorInfo.IME_ACTION_DONE);
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
    }
    
    private void setListAdaptor()
    {
        mAdaptor = new PinnedHeaderAdapter(this, mListItems, mListSectionPos);
        mListView.setAdapter(mAdaptor);
        mListView.setOnItemClickListener(new OnItemClickListener()
        {
            
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                //Logger.e("TAG", "countryName---->" + listCountry.get(position));
                //------------------做搜索时修改Tony----------------------
                ViewGroup vg = (ViewGroup)view;
                TextView tv_title = (TextView) vg.getChildAt(0);
                String countryName = tv_title.getText().toString();
                //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>countryName"+name);
                //---------------------------------------------
                if (id == -1)
                {
                    return;
                }
                Intent intent = new Intent();
                //intent.putExtra("countryName", listCountry.get(position));
                intent.putExtra("countryName", countryName);
                intent.putExtra("countryModel", countryModel);
                ChangeCountryActivity.this.setResult(ServerConstant.Parameter.CHANGE_COUNTRY_RESULTCODE, intent);
                mAdaptor.notifyDataSetInvalidated();
                ChangeCountryActivity.this.finish();
            }
            
        });
        
        LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
        
        View pinnedHeaderView = inflater.inflate(R.layout.section_row_view, mListView, false);
        mListView.setPinnedHeaderView(pinnedHeaderView);
        
        IndexBarView indexBarView = (IndexBarView)inflater.inflate(R.layout.index_bar_view, mListView, false);
        indexBarView.setData(mListView, mListItems, mListSectionPos);
        mListView.setIndexBarView(indexBarView);
        
        View previewTextView = inflater.inflate(R.layout.preview_view, mListView, false);
        mListView.setPreviewView(previewTextView);
        
        // for configure pinned header view on scroll change
        mListView.setOnScrollListener(mAdaptor);
    }
    
    public class ListFilter extends Filter
    {
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {
            
            String constraintStr = constraint.toString().toLowerCase(Locale.getDefault());
            FilterResults result = new FilterResults();
            
            if (constraint != null && constraint.toString().length() > 0)
            {
                ArrayList<String> filterItems = new ArrayList<String>();
                
                synchronized (this)
                {
                    for (String item : listCountry)
                    {
                        if (item.toLowerCase(Locale.getDefault()).startsWith(constraintStr))
                        {
                            filterItems.add(item);
                        }
                    }
                    result.count = filterItems.size();
                    result.values = filterItems;
                }
            }
            else
            {
                synchronized (this)
                {
                    result.count = listCountry.size();
                    result.values = listCountry;
                }
            }
            return result;
        }
        
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results)
        {
            ArrayList<String> filtered = (ArrayList<String>)results.values;
            
            new Poplulate().execute(filtered);
        }
        
    }
    
    private class Poplulate extends AsyncTask<ArrayList<String>, Void, Void>
    {
        
        @Override
        protected void onPreExecute()
        {
            // show loading indicator
            super.onPreExecute();
        }
        
        @Override
        protected Void doInBackground(ArrayList<String>... params)
        {
            mListItems.clear();
            mListSectionPos.clear();
            ArrayList<String> items = params[0];
            if (listCountry.size() > 0)
            {
                
                // NOT forget to sort array
                Collections.sort(items, new SortIgnoreCase());
                
                String prev_section = "";
                for (String current_item : items)
                {
                    String current_section = current_item.substring(0, 1).toUpperCase(Locale.getDefault());
                    
                    if (!prev_section.equals(current_section))
                    {
                        mListItems.add(current_section);
                        //mListItems.add(current_item);
                        // array list of section positions
                        mListSectionPos.add(mListItems.indexOf(current_section));
                        prev_section = current_section;
                    }
                    //-------------修改代码ByTony--------------------------
//                    else
//                    {
                        mListItems.add(current_item);
//                    }
                    //----------------------------------------------------
                }
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(Void result)
        {
            if (!isCancelled())
            {
                //                if (mListItems.size() <= 0)
                //                {
                //                    showEmptyText(mListView, mLoadingView, mEmptyView);
                //                }
                //                else
                //                {
                setListAdaptor();
                //                    showContent(mListView, mLoadingView, mEmptyView);
                //                }
            }
            super.onPostExecute(result);
        }
    }
    
    public class SortIgnoreCase implements Comparator<String>
    {
        public int compare(String s1, String s2)
        {
            return s1.compareToIgnoreCase(s2);
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        if (mListItems != null && mListItems.size() > 0)
        {
            outState.putStringArrayList("mListItems", mListItems);
        }
        if (mListSectionPos != null && mListSectionPos.size() > 0)
        {
            outState.putIntegerArrayList("mListSectionPos", mListSectionPos);
        }
        
        super.onSaveInstanceState(outState);
    }
}
